package main

import (
	"crypto/md5"
	"errors"
	"fmt"
	"encoding/hex"
	"crypto/cipher"
	"crypto/des"
	"bytes"
)

func main(){
	fmt.Println(len("o8yIHj8PfCdfEW1IvPE6aEsHx2oo"))
}


func testMD5(content string){
	h :=md5.New()
	h.Write([]byte(content))
	cp := h.Sum(nil)
	fmt.Println(cp)
	fmt.Println(hex.EncodeToString(cp))
}



func DesEncrypt(origData, key []byte) ([]byte, error) {
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, err
	}
	origData = PKCS5Padding(origData, block.BlockSize())
	// origData = ZeroPadding(origData, block.BlockSize())
	blockMode := cipher.NewCBCEncrypter(block, key)
	crypted := make([]byte, len(origData))
	// 根据CryptBlocks方法的说明，如下方式初始化crypted也可以
	// crypted := origData
	blockMode.CryptBlocks(crypted, origData)
	return crypted, nil
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func DesDecrypt(crypted, key []byte) ([]byte, error) {
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockMode := cipher.NewCBCDecrypter(block, key)
	origData := make([]byte, len(crypted))
	// origData := crypted
	blockMode.CryptBlocks(origData, crypted)
	origData = PKCS5UnPadding(origData)
	// origData = ZeroUnPadding(origData)
	return origData, nil
}

func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	// 去掉最后一个字节 unpadding 次
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}

func TestSecret(){
	res,err:= DesEncrypt([]byte("Hi World"),[]byte("thisisat"))
	if err!=nil{
		fmt.Println("Encry  : ",err)
		return
	}
	fmt.Println(string(res))
	resO,err:= DesDecrypt(res,[]byte("thisisat"))
	if err!=nil{
		fmt.Println("Decty : ",err)
		return
	}
	fmt.Println("------------")
	fmt.Println(string(resO))
}

func DESEncrypt(text,keyt string) (string, error) {
	src := []byte(text)
	key :=[]byte(keyt)
	block, err := des.NewCipher(key)
	if err != nil {
		return "", err
	}
	bs := block.BlockSize()
	src = padding(src, bs)
	if len(src)%bs != 0 {
		return "", errors.New("Need a multiple of the blocksize")
	}
	out := make([]byte, len(src))
	dst := out
	for len(src) > 0 {
		block.Encrypt(dst, src[:bs])
		src = src[bs:]
		dst = dst[bs:]
	}
	return hex.EncodeToString(out), nil
}

func padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{0}, padding)
	return append(ciphertext, padtext...)
}


func test1(){
	res,_:= DESEncrypt("123456789123456789123456789123","tigerAaa")
	fmt.Println(res)
	fmt.Println(len(res))
}